<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Category extends CI_Controller {

    var $role;
    var $user_id;
    
    public function __construct() {
        parent::__construct();
        $this->load->model('categories');
        $this->load->helper('url');
        $this->load->library('session');
        $this->role = $this->session->userdata('role');
        $this->user_id = $this->session->userdata('user_id');
        $this->_authenticate();
    }
    
    public function index() {
        $this->_error();
    }
    
    private function _error() {
        show_404();
    }

    //AUTHENTICATION//

    private function _authenticate() {
        if ($this->session->userdata('islogged') == null) {
            redirect(base_url() . 'cp/login');
        }
    }

    private function _is_admin() {
        if ($this->role != 0) {
            $this->_error();
        }
    }
    
    private function _authorize($user_id) {
        if (($this->user_id != $user_id) && ($this->role != 0)){
            $this->_error();
        }
    }
    
    //BASIC FUNCTION//
    
    public function add() {
        $data['category_name'] = $this->input->post('fname');
        $data['category_published'] = $this->input->post('fpublished');
        $this->categories->insert($data);
        $this->session->set_flashdata('category', 'Category Added');
        redirect(base_url() . 'cp/list_category');
    }
    
    public function edit() {
        $category_id = $this->session->userdata('edit_category_id');
        $result = $this->categories->get_category_by_id($category_id);
        $data['category_name'] = $this->input->post('fname');
        $data['category_published'] = $this->input->post('fpublished');
        $this->categories->update_by_id($category_id,$data);
        $this->session->set_flashdata('category', 'Category Edited');
        redirect(base_url() . 'cp/list_category');
    }
    
    public function delete($category_id){
        $this->_is_admin();
        $result = $this->categories->get_category_by_id($category_id);
        $this->categories->delete_by_id($category_id);
        $this->session->set_flashdata('category', 'Category Deleted');
        redirect(base_url() . 'cp/list_category');
    }
}
